package com.qf.smartplatform.controller.advice;/*
*王浩政 
*whz
2022/9/9
10:38
*小米商城
*/

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.smartplatform.constans.ResultCode;
import com.qf.smartplatform.dto.R;
import com.qf.smartplatform.exceptions.MyBaseException;
import org.springframework.validation.beanvalidation.SpringValidatorAdapter;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Map;

@RestControllerAdvice
public class MyControllerAdvice {

    public ObjectMapper objectMapper;

    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    /*
    * 处理我们的自定义异常
    * */
    @ExceptionHandler(MyBaseException.class)
    public R processBaseException(MyBaseException exception){
        exception.printStackTrace();
        return R.getResult(exception.getCode(),exception.getMessage());
    }

    /*
    * 处理请求参数校验的异常
    * */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R processMethodArgumentNotValidException(MethodArgumentNotValidException exception){
        //exception.printStackTrace();

//        exception.getBindingResult().getAllErrors().forEach(objectError -> {
//            String defaultMessage=objectError.getDefaultMessage();
//            System.out.println(defaultMessage);
//        });
        String defaultMessage = exception.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        try {
            //将我们自定义的异常与字符串转成map，然后从里边获取到我们传递的code和msg
            Map map = objectMapper.readValue(defaultMessage, Map.class);
            return R.getResult((Integer)map.get("code"), (String) map.get("msg"));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return R.ERROR();
    }

    @ExceptionHandler(MyBaseException.class)
    public R processBaseException(Exception exception){
        exception.printStackTrace();
        return R.getResult(ResultCode.FAIL,"网络异常，请检查您你异常");
    }
}
